Link to notebook
Link to github repo.
library(tidyverse)
library(readxl)
library(phyloseq)
library(Biostrings)
#library(phangorn)
library(readr)
library(seqinr)
library(decontam)
library(ape)
library(vegan)
#library(philr)
library(RColorBrewer)
library(microbiome)
#library(DESeq2)
library(compositions);
library(cowplot)
library(plotly)
library(htmlwidgets)
library(withr)
library(lubridate)
metadata <- read_csv("sample_data.csv")
[36m──[39m [1m[1mColumn specification[1m[22m [36m─────────────────────────────────────────────────────────────────[39m
cols(
SampleID = [31mcol_character()[39m,
`Year.Trawl#` = [31mcol_character()[39m,
Datecode = [32mcol_double()[39m,
Date = [31mcol_character()[39m,
Month = [32mcol_double()[39m,
Year = [32mcol_double()[39m,
Bayside = [31mcol_character()[39m,
Station = [31mcol_character()[39m,
Habitat = [31mcol_character()[39m,
DO = [32mcol_double()[39m,
Salinity = [32mcol_double()[39m,
Temperature = [32mcol_double()[39m
)
Import count table and taxonomy file. I slightly modified otutable.csv in Excel to otutable_mod.csv to remove the quotes around seq names and put NA placehoder as first col name (which was above row names)
# Import Count table. Skip first row of tsv file, which is just some text
count_table <- read_table2("results/otutable_mod.csv")
Missing column names filled in: 'X1' [1]
[36m──[39m [1m[1mColumn specification[1m[22m [36m─────────────────────────────────────────────────────────────────[39m
cols(
.default = col_double(),
X1 = [31mcol_character()[39m
)
[36mℹ[39m Use [38;5;235m[48;5;253m[38;5;235m[48;5;253m`spec()`[48;5;253m[38;5;235m[49m[39m for the full column specifications.
colnames(count_table)[1] <- "SampleID"
# Import taxonomy of ASVs
taxonomy <- read_csv(file="results/tax_sequences_blast_taxonomy.csv")
Missing column names filled in: 'X1' [1]Duplicated column names deduplicated: 'RefSeq_Tax_ID' => 'RefSeq_Tax_ID_1' [18]
[36m──[39m [1m[1mColumn specification[1m[22m [36m─────────────────────────────────────────────────────────────────[39m
cols(
X1 = [32mcol_double()[39m,
ASV_ID = [31mcol_character()[39m,
ref_seq_ID = [31mcol_character()[39m,
PID = [32mcol_double()[39m,
alnmt_len = [32mcol_double()[39m,
mismatch = [32mcol_double()[39m,
eval = [32mcol_double()[39m,
bscore = [32mcol_double()[39m,
RefSeq_Tax_ID = [32mcol_double()[39m,
Ref_Seq_title = [31mcol_character()[39m,
superkingdom = [31mcol_character()[39m,
phylum = [31mcol_character()[39m,
class = [31mcol_character()[39m,
order = [31mcol_character()[39m,
family = [31mcol_character()[39m,
genus = [31mcol_character()[39m,
species = [31mcol_character()[39m,
RefSeq_Tax_ID_1 = [32mcol_double()[39m
)
# remove first col of sequential numbers
taxonomy[,1] <- NULL
# filter out sequences with low PID (recommended by Sara)
taxonomy <- filter(taxonomy, PID > 92)
# remove BLAST metadata and just retain taxonomy (necessary for further processing below)
drop.cols <- c(colnames(taxonomy)[2:9],'RefSeq_Tax_ID_1')
taxonomy <- select(taxonomy, -one_of(drop.cols))
# And import the Common names, as curated by Sara. Join to taxonomy
commonnames <- read_excel("Trawls MASTER 2020 _mod_ES.xlsx",7)
commonnames
taxonomy <- left_join(taxonomy, commonnames, by = "ASV_ID")
taxonomy
NA
Filtering removed seqs 110, 332 (Gobiosoma ginsburgi and Belone belone) Note for Sara should we consider setting this at 97% which is more robust and still leaves 334 unique ASVs (rather than 379 with the 92% cutoff in the settings above)
Preview datasets
count_table
taxonomy
metadata
I want to use the phyloseq package for some plotting/ statistics, which first requires making phyloseq objects out of each of input data tables-
count_table_matrix <- as.matrix(count_table[,2:392]) # convert count table to matrix, leaving out character column of sample ID
rownames(count_table_matrix) <- count_table$SampleID # add back in Sample IDs as row names
ASV = otu_table(count_table_matrix, taxa_are_rows = FALSE)
taxonomy_matrix <- as.matrix(taxonomy[,2:9])
rownames(taxonomy_matrix) <- taxonomy$ASV_ID
TAX = tax_table(taxonomy_matrix)
META = sample_data(data.frame(metadata, row.names = metadata$`SampleID`))
First check that the inputs are in compatible formats by checking for ASV names with the phyloseq function, taxa_names
head(taxa_names(TAX))
[1] "Seq_1" "Seq_2" "Seq_3" "Seq_4" "Seq_5" "Seq_6"
head(taxa_names(ASV))
[1] "Seq_1" "Seq_2" "Seq_3" "Seq_4" "Seq_5" "Seq_6"
And check sample names were also detected
# Modify taxa names in ASV, which are formatted with the sample ID, underscor, fastq ID. Don't need this fastq ID anymore and want it to match the sample names from metadata
sample_names(ASV) <- sample_names(ASV) %>%
str_replace_all(pattern = "_S[:digit:]+",replacement = "")
head(sample_names(ASV))
[1] "T1PosCon" "T1S10" "T1S11" "T1S1" "T1S2" "T1S3"
head(sample_names(META))
[1] "T1PosCon" "T1S1" "T1S2" "T1S3" "T1S5" "T1S6"
And make the phyloseq object
ps <- phyloseq(ASV, TAX, META)
rarecurve(otu_table(ps), step=50, cex=0.5)
empty rows removed
# save as .eps
setEPS()
postscript("Figures/rarefaction.eps")
rarecurve(otu_table(ps), step=50, cex=0.5)
empty rows removed
dev.off()
quartz_off_screen
2
Most samples look like they were sampled to completion. Be weary of T3S11, T1S2, and maybe T4S5
Check some features of the phyloseq object
rank_names(ps)
[1] "superkingdom" "phylum" "class" "order" "family"
[6] "genus" "species" "CommonName"
unique(tax_table(ps)[, "superkingdom"])
Taxonomy Table: [2 taxa by 1 taxonomic ranks]:
superkingdom
Seq_1 "Eukaryota"
Seq_377 NA
unique(tax_table(ps)[, "phylum"])
Taxonomy Table: [3 taxa by 1 taxonomic ranks]:
phylum
Seq_1 "Chordata"
Seq_368 "Arthropoda"
Seq_377 NA
unique(tax_table(ps)[, "class"])
Taxonomy Table: [5 taxa by 1 taxonomic ranks]:
class
Seq_1 "Actinopteri"
Seq_63 "Mammalia"
Seq_362 "Chondrichthyes"
Seq_368 "Insecta"
Seq_377 NA
There are some ASVs with NA as superkingdom, phylum, or class annotation- delete these.
ps <- subset_taxa(ps, !is.na(superkingdom) & !is.na(phylum) & !is.na(class))
unique(tax_table(ps)[, "superkingdom"])
Taxonomy Table: [1 taxa by 1 taxonomic ranks]:
superkingdom
Seq_1 "Eukaryota"
unique(tax_table(ps)[, "phylum"])
Taxonomy Table: [2 taxa by 1 taxonomic ranks]:
phylum
Seq_1 "Chordata"
Seq_368 "Arthropoda"
unique(tax_table(ps)[, "class"])
Taxonomy Table: [4 taxa by 1 taxonomic ranks]:
class
Seq_1 "Actinopteri"
Seq_63 "Mammalia"
Seq_362 "Chondrichthyes"
Seq_368 "Insecta"
nrow(tax_table(ps)) # number of ASVs left
[1] 378
378 ASVs still remain…
Also check class Mammalia, to see if contamination or real:
tax_table(subset_taxa(ps, class == 'Mammalia'))
Taxonomy Table: [8 taxa by 8 taxonomic ranks]:
superkingdom phylum class order family genus
Seq_63 "Eukaryota" "Chordata" "Mammalia" "Primates" "Hominidae" "Homo"
Seq_88 "Eukaryota" "Chordata" "Mammalia" "Artiodactyla" "Suidae" "Sus"
Seq_157 "Eukaryota" "Chordata" "Mammalia" "Primates" "Hominidae" "Homo"
Seq_343 "Eukaryota" "Chordata" "Mammalia" "Carnivora" "Felidae" "Felis"
Seq_369 "Eukaryota" "Chordata" "Mammalia" "Artiodactyla" "Bovidae" "Bos"
Seq_378 "Eukaryota" "Chordata" "Mammalia" "Primates" "Hominidae" "Homo"
Seq_383 "Eukaryota" "Chordata" "Mammalia" "Primates" "Hominidae" "Homo"
Seq_389 "Eukaryota" "Chordata" "Mammalia" "Primates" "Hominidae" "Homo"
species CommonName
Seq_63 "Homo sapiens" "Human"
Seq_88 "Sus scrofa" "Wild boar"
Seq_157 "Homo sapiens" "Human"
Seq_343 "Felis catus" "Cat"
Seq_369 "Bos taurus" "Cattle"
Seq_378 "Homo sapiens" "Human"
Seq_383 "Homo sapiens" "Human"
Seq_389 "Homo sapiens" "Human"
These are human, wild boar, cat (…cat lady), and cattle. All are contamination so delete all Mammalia
ps <- subset_taxa(ps, !class == 'Mammalia')
unique(tax_table(ps)[, "class"])
Taxonomy Table: [3 taxa by 1 taxonomic ranks]:
class
Seq_1 "Actinopteri"
Seq_362 "Chondrichthyes"
Seq_368 "Insecta"
Next check the “Insecta” entries
tax_table(subset_taxa(ps, class == 'Insecta'))
Taxonomy Table: [2 taxa by 8 taxonomic ranks]:
superkingdom phylum class order family genus
Seq_368 "Eukaryota" "Arthropoda" "Insecta" "Hymenoptera" "Formicidae" "Linepithema"
Seq_380 "Eukaryota" "Arthropoda" "Insecta" "Hymenoptera" "Formicidae" "Linepithema"
species CommonName
Seq_368 "Linepithema humile" "Ant"
Seq_380 "Linepithema humile" "Ant"
The onlly Insecta is Linepithema humile, which are ants so delete these too..
ps <- subset_taxa(ps, !class == 'Insecta')
unique(tax_table(ps)[, "class"])
Taxonomy Table: [2 taxa by 1 taxonomic ranks]:
class
Seq_1 "Actinopteri"
Seq_362 "Chondrichthyes"
Check overall how ASVs there are per sample
# First aglomerate the ASVs at the phylum level using the phyloseq function, tax_glom
superkingdomGlommed = tax_glom(ps, "superkingdom")
# and plot
plot_bar(superkingdomGlommed, x = "Sample")
ggsave(filename = "Figures/seqdepth.eps", plot = plot_bar(superkingdomGlommed, x = "Sample"), units = c("in"), width = 9, height = 6, dpi = 300, )# and save
Total sequences reveals certain samples had very low sequencing effort: T1S7, T1S8, T3S11, and, not as bad, T1S2 and T4S5
The rarefaction analysis also showed T1S2 and T4S5 samples were likely not sequenced to completion. Therefore remove these 5 samples from analysis
ps <- subset_samples(ps, !SampleID == "T1S7" & !SampleID == "T1S8" & !SampleID == "T3S11" & !SampleID == "T1S2" & !SampleID == "T4S5")
ps
phyloseq-class experiment-level object
otu_table() OTU Table: [ 368 taxa and 50 samples ]
sample_data() Sample Data: [ 50 samples by 12 sample variables ]
tax_table() Taxonomy Table: [ 368 taxa by 8 taxonomic ranks ]
50 samples remaining with 368 ASVs
Remove Pos Controls (all hits in positive controls are the same family- I assume this is expected)
ps <- subset_samples(ps, !SampleID == "T1PosCon" & !SampleID == "T2PosCon" & !SampleID == "T3PosCon")
ps
phyloseq-class experiment-level object
otu_table() OTU Table: [ 368 taxa and 47 samples ]
sample_data() Sample Data: [ 47 samples by 12 sample variables ]
tax_table() Taxonomy Table: [ 368 taxa by 8 taxonomic ranks ]
And lastly, correct some taxonomy: According to Sara, Engraulis encrasicolus (European anchovy) should be Anchoa mitchilli (Bay anchovy):
tax_table(ps) <- gsub(tax_table(ps), pattern = "Engraulis encrasicolus", replacement = "Anchoa mitchilli")
47 samples remainwith 368 unique ASVs
For plotting, use relative abundances (# of ASV sequences/sum total sequences in sample), calculated easily using microbiome::transform
ps_ra <- microbiome::transform(ps, transform = "compositional")
Export the relative abundance matrix so Sara can have it:
# Extract abundance matrix from the phyloseq object
RelAbun_matrix = as(otu_table(ps_ra), "matrix")
# Coerce to data.frame
RelAbun_dataframe = as.data.frame(RelAbun_matrix)
# Export
write.csv(RelAbun_dataframe,"results/otutable_relabun.csv", row.names = TRUE)
Then aglomerate the ASVs at the family level using the phyloseq function, tax_glom
familyGlommed_RA = tax_glom(ps_ra, "family")
family_barplot <- plot_bar(familyGlommed_RA, x = "Sample", fill = "family")
family_barplot
NOTES for Sara
Agglomerate by species to see if I get the same 38 unique species Sara sees:
speciesGlommed_RA = tax_glom(ps_ra, "CommonName")
speciesGlommed_RA
phyloseq-class experiment-level object
otu_table() OTU Table: [ 43 taxa and 47 samples ]
sample_data() Sample Data: [ 47 samples by 12 sample variables ]
tax_table() Taxonomy Table: [ 43 taxa by 8 taxonomic ranks ]
tax_table(speciesGlommed_RA)
Taxonomy Table: [43 taxa by 8 taxonomic ranks]:
superkingdom phylum class order family
Seq_1 "Eukaryota" "Chordata" "Actinopteri" "Atheriniformes" "Atherinopsidae"
Seq_2 "Eukaryota" "Chordata" "Actinopteri" "Clupeiformes" "Clupeidae"
Seq_3 "Eukaryota" "Chordata" "Actinopteri" "Clupeiformes" "Engraulidae"
Seq_4 "Eukaryota" "Chordata" "Actinopteri" "Scombriformes" "Pomatomidae"
Seq_5 "Eukaryota" "Chordata" "Actinopteri" "Lutjaniformes" "Lutjanidae"
Seq_6 "Eukaryota" "Chordata" "Actinopteri" "Pleuronectiformes" "Paralichthyidae"
Seq_7 "Eukaryota" "Chordata" "Actinopteri" "Clupeiformes" "Clupeidae"
Seq_9 "Eukaryota" "Chordata" "Actinopteri" "Gobiiformes" "Gobiidae"
Seq_10 "Eukaryota" "Chordata" "Actinopteri" "Pleuronectiformes" "Scophthalmidae"
Seq_11 "Eukaryota" "Chordata" "Actinopteri" "Perciformes" "Serranidae"
Seq_12 "Eukaryota" "Chordata" "Actinopteri" "Spariformes" "Sparidae"
Seq_15 "Eukaryota" "Chordata" "Actinopteri" NA "Sciaenidae"
Seq_16 "Eukaryota" "Chordata" "Actinopteri" NA "Sciaenidae"
Seq_17 "Eukaryota" "Chordata" "Actinopteri" "Labriformes" "Labridae"
Seq_19 "Eukaryota" "Chordata" "Actinopteri" "Perciformes" "Cottidae"
Seq_20 "Eukaryota" "Chordata" "Actinopteri" "Pleuronectiformes" "Pleuronectidae"
Seq_21 "Eukaryota" "Chordata" "Actinopteri" NA "Moronidae"
Seq_22 "Eukaryota" "Chordata" "Actinopteri" "Syngnathiformes" "Syngnathidae"
Seq_30 "Eukaryota" "Chordata" "Actinopteri" "Pleuronectiformes" "Paralichthyidae"
Seq_33 "Eukaryota" "Chordata" "Actinopteri" NA "Sciaenidae"
Seq_34 "Eukaryota" "Chordata" "Actinopteri" "Labriformes" "Labridae"
Seq_36 "Eukaryota" "Chordata" "Actinopteri" "Anguilliformes" "Anguillidae"
Seq_38 "Eukaryota" "Chordata" "Actinopteri" "Scombriformes" "Scombridae"
Seq_40 "Eukaryota" "Chordata" "Actinopteri" "Perciformes" "Gasterosteidae"
Seq_44 "Eukaryota" "Chordata" "Actinopteri" "Cyprinodontiformes" "Fundulidae"
Seq_50 "Eukaryota" "Chordata" "Actinopteri" "Atheriniformes" "Atherinopsidae"
Seq_52 "Eukaryota" "Chordata" "Actinopteri" "Gadiformes" "Phycidae"
Seq_54 "Eukaryota" "Chordata" "Actinopteri" "Scombriformes" "Scombridae"
Seq_57 "Eukaryota" "Chordata" "Actinopteri" "Perciformes" "Triglidae"
Seq_67 "Eukaryota" "Chordata" "Actinopteri" "Scombriformes" "Scombridae"
Seq_82 "Eukaryota" "Chordata" "Actinopteri" NA "Sciaenidae"
Seq_84 "Eukaryota" "Chordata" "Actinopteri" "Gadiformes" "Gadidae"
Seq_102 "Eukaryota" "Chordata" "Actinopteri" "Clupeiformes" "Engraulidae"
Seq_103 "Eukaryota" "Chordata" "Actinopteri" "Perciformes" "Cottidae"
Seq_115 "Eukaryota" "Chordata" "Actinopteri" "Cyprinodontiformes" "Fundulidae"
Seq_119 "Eukaryota" "Chordata" "Actinopteri" "Gadiformes" "Phycidae"
Seq_139 "Eukaryota" "Chordata" "Actinopteri" "Batrachoidiformes" "Batrachoididae"
Seq_141 "Eukaryota" "Chordata" "Actinopteri" "Scombriformes" "Scombridae"
Seq_181 "Eukaryota" "Chordata" "Actinopteri" "Tetraodontiformes" "Tetraodontidae"
Seq_231 "Eukaryota" "Chordata" "Actinopteri" "Gadiformes" "Merlucciidae"
Seq_359 "Eukaryota" "Chordata" "Actinopteri" "Perciformes" "Triglidae"
Seq_362 "Eukaryota" "Chordata" "Chondrichthyes" "Myliobatiformes" "Myliobatidae"
Seq_372 "Eukaryota" "Chordata" "Chondrichthyes" "Carcharhiniformes" "Triakidae"
genus species CommonName
Seq_1 "Menidia" "Menidia menidia" "Atlantic silverside"
Seq_2 "Brevoortia" "Brevoortia tyrannus" "Atlantic menhaden"
Seq_3 "Engraulis" "Anchoa mitchilli" "Bay anchovy"
Seq_4 "Pomatomus" "Pomatomus saltatrix" "Bluefish"
Seq_5 "Lutjanus" "Lutjanus griseus" "Grey snapper"
Seq_6 "Paralichthys" "Paralichthys dentatus" "Summer flounder"
Seq_7 "Alosa" "Alosa mediocris" "Hickory shad"
Seq_9 "Gobiosoma" "Gobiosoma ginsburgi" "Seaboard goby"
Seq_10 "Scophthalmus" "Scophthalmus aquosus" "Windowpane flounder"
Seq_11 "Centropristis" "Centropristis striata" "Black seabass"
Seq_12 "Stenotomus" "Stenotomus chrysops" "Scup"
Seq_15 "Leiostomus" "Leiostomus xanthurus" "Spot"
Seq_16 "Menticirrhus" "Menticirrhus saxatilis" "Northern kingfish"
Seq_17 "Tautoga" "Tautoga onitis" "Tautog"
Seq_19 "Myoxocephalus" "Myoxocephalus aenaeus" "Grubby sculpin"
Seq_20 "Pseudopleuronectes" "Pseudopleuronectes americanus" "Winter flounder"
Seq_21 "Morone" "Morone saxatilis" "Striped bass"
Seq_22 "Syngnathus" "Syngnathus fuscus" "Northern pipefish"
Seq_30 "Etropus" "Etropus microstomus" "Smallmouth flounder"
Seq_33 "Cynoscion" "Cynoscion regalis" "Weakfish"
Seq_34 "Tautogolabrus" "Tautogolabrus adspersus" "Cunner"
Seq_36 "Anguilla" "Anguilla rostrata" "American eel"
Seq_38 "Thunnus" "Thunnus obesus" "Bigeye tuna"
Seq_40 "Apeltes" "Apeltes quadracus" "Stickleback"
Seq_44 "Fundulus" "Fundulus majalis" "Striped killifish"
Seq_50 "Membras" "Membras martinica" "Rough silverside"
Seq_52 "Urophycis" "Urophycis floridana" "Spotted hake"
Seq_54 "Scomber" "Scomber japonicus" "Chub mackerel"
Seq_57 "Prionotus" "Prionotus carolinus" "Northern searobin"
Seq_67 "Thunnus" "Thunnus thynnus" "Atlantic bluefin tuna"
Seq_82 "Bairdiella" "Bairdiella chrysoura" "American silver perch"
Seq_84 "Microgadus" "Microgadus tomcod" "Atlantic tomcod"
Seq_102 "Engraulis" "Engraulis mordax" "Bay anchovy"
Seq_103 "Myoxocephalus" "Myoxocephalus quadricornis" "Fourhorn sculpin"
Seq_115 "Fundulus" "Fundulus heteroclitus" "Mummichog"
Seq_119 "Urophycis" "Urophycis floridana" "Red hake"
Seq_139 "Opsanus" "Opsanus tau" "Oyster toadfish"
Seq_141 "Katsuwonus" "Katsuwonus pelamis" "Skipjack tuna"
Seq_181 "Sphoeroides" "Sphoeroides maculatus" "Northern puffer"
Seq_231 "Merluccius" "Merluccius bilinearis" "Silver hake"
Seq_359 "Prionotus" "Prionotus evolans" "Striped searobin"
Seq_362 "Rhinoptera" "Rhinoptera bonasus" "Cownose ray"
Seq_372 "Mustelus" "Mustelus canis" "Dusky smooth-hound shark"
NOTES for Sara
Based on my previous scripts with Cariaco Eukaryotic data
# convert ps object to dataframe using phyloseq's psmelt
species_df <- psmelt(speciesGlommed_RA)
# replace zeroes in the table with NA
species_df[species_df == 0] <- NA
# and remove rows with NAs in abundance (this is so they don't appear as small dots in plot)
species_df <- filter(species_df, !is.na(Abundance))
Plot by species, scientific name
speciesbubbleplot_eDNA_sciname <- ggplot(species_df, aes(x = Station, y = fct_rev(species), color = Station)) + # the fancy stuff around y (species) helps to present it in reverse order in the plot (from top to btm alphabetically)
geom_point(aes(size = Abundance, fill = Station), color = "black", pch = 21)+
scale_size(range = c(1,15)) +
scale_size_area(breaks = c(0,.25,.5,.75,1), max_size = 6)+
xlab("")+
ylab("")+
labs(size="Relative Abundance")+
theme_bw() +
scale_fill_brewer(palette="Paired") +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
facet_grid(Datecode~Bayside, scales = "free", space = "free", drop= TRUE)
Scale for 'size' is already present. Adding another scale for 'size', which will
replace the existing scale.
speciesbubbleplot_eDNA_sciname
Plot by species common name
speciesbubbleplot_eDNA_comname <- ggplot(species_df, aes(x = Station, y = fct_rev(CommonName), color = Station)) + # the fancy stuff around y (CommonName) helps to present it in reverse order in the plot (from top to btm alphabetically)
geom_point(aes(size = Abundance, fill = Station), color = "black", pch = 21)+
scale_size(range = c(1,15)) +
scale_size_area(breaks = c(0,.25,.5,.75,1), max_size = 6)+
xlab("")+
ylab("")+
labs(size="Relative Abundance")+
theme_bw() +
scale_fill_brewer(palette="Paired") +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
facet_grid(Datecode~Bayside, scales = "free", space = "free", drop= TRUE)
Scale for 'size' is already present. Adding another scale for 'size', which will
replace the existing scale.
speciesbubbleplot_eDNA_comname
Exportfigures
ggsave(filename = "Figures/speciesbubbleplot_eDNA_sciname.eps", plot = speciesbubbleplot_eDNA_sciname, units = c("in"), width = 7, height = 12, dpi = 300)
ggsave(filename = "Figures/speciesbubbleplot_eDNA_comname.eps", plot = speciesbubbleplot_eDNA_comname, units = c("in"), width = 7, height = 12, dpi = 300)
NOTE on above. The common name plot has two entries in the Bay anchovy row because, as mentioned above, there are two different species name that are labelled as Bay Anchovy. Is it OK to group these as same species (Anchoa mitchilli)
# import 4th sheet from Excel file which contains morphometric data for each individual collected for every date
trawl_master <- read_excel("Trawls MASTER 2020 _mod_ES.xlsx",4)
trawl_master
# and import 6th sheet which is station info
stations <- read_excel("Trawls MASTER 2020 _mod_ES.xlsx",6)
stations
NA
Make an equivalent to an OTU table, grouping by date and location and representing counts for every unique species
trawl_counts <- trawl_master %>%
group_by(DATECODE, STATION_NO, CommonName) %>%
tally(name = "count")
trawl_counts
and link station names instead of numbers to count table
trawl_counts <- left_join(trawl_counts, stations, by = "STATION_NO")
trawl_counts
Remove 09/16/20 since there is no equivalent eDNA from that date
trawl_counts <- trawl_counts %>%
filter(DATECODE != "20200916")
trawl_counts
speciesbubbleplot_trawl_comname <- ggplot(trawl_counts, aes(x = STATION_NA, y = fct_rev(CommonName), color = STATION_NA)) +
geom_point(aes(size = log10(count), fill = STATION_NA), color = "black", pch = 21)+
scale_size(range = c(1,15)) +
scale_size_area(breaks = c(.01,.1, .3, .5, 1, 3), max_size = 6)+
xlab("")+
ylab("")+
labs(size="Log(counts)", fill = "Station")+
theme_bw() +
scale_fill_brewer(palette="Paired") +
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank()) +
facet_grid(DATECODE~BAYSIDE, scales = "free", space = "free", drop= TRUE)
Scale for 'size' is already present. Adding another scale for 'size', which will
replace the existing scale.
speciesbubbleplot_trawl_comname
Export figure
ggsave(filename = "Figures/speciesbubbleplot_trawl_comname.eps", plot = speciesbubbleplot_trawl_comname, units = c("in"), width = 6.75, height = 13, dpi = 300)
Count unique species across all stations, grouped by date, for each method (trawl, eDNA)
trawl_uniques <- trawl_counts %>%
group_by(DATECODE, CommonName) %>%
summarise(Trawl_Count = sum(count, na.rm=TRUE))
`summarise()` regrouping output by 'DATECODE' (override with `.groups` argument)
trawl_uniques
eDNA_uniques <- species_df%>%
group_by(Datecode, CommonName) %>%
summarise(eDNA_RelAbun = sum(Abundance, na.rm=TRUE))
`summarise()` regrouping output by 'Datecode' (override with `.groups` argument)
eDNA_uniques
# Combine into one dataframe
trawl_eDNA_abun_table <- full_join(trawl_uniques, eDNA_uniques, by=c("CommonName" = "CommonName", "DATECODE" = "Datecode"))
trawl_eDNA_abun_table
Count total number of species from each method for each date
eDNA_richness <- tally(eDNA_uniques, name = "eDNA")
trawl_richness <- tally(trawl_uniques, name = "trawl")
speciesrichness <- full_join(eDNA_richness, trawl_richness, c("Datecode" = "DATECODE"))
speciesrichness <- pivot_longer(speciesrichness, !Datecode, names_to = "Method", values_to = "Richness")
speciesrichness$Datecode <- ymd(speciesrichness$Datecode) # convert to date format (better for plotting)
speciesrichness
Plot side-by-side
species_richness_plot <- ggplot(speciesrichness, aes(x =Datecode, y = Richness)) +
geom_line(aes(color = Method), size = 3) +
theme_bw() +
xlab("") +
ylab("Species Richness")
species_richness_plot
# export plot
ggsave(filename = "Figures/species_richness_plot.eps", plot = species_richness_plot, units = c("in"), width = 4, height = 3, dpi = 300)
NOTE on above- come back and remove trawl samples for which the eDNA samples were removed so that this is a fair comparison. Also remove non-MiFISH species from trawl? Check with Sara
Sum total number of species across all dates/ stations for entire study
species_sums_abun_table <- trawl_eDNA_abun_table %>%
group_by(CommonName) %>%
summarise(Trawl = sum(Trawl_Count, na.rm=TRUE), eDNA = (sum(eDNA_RelAbun, na.rm=TRUE))) %>%
pivot_longer(!CommonName, names_to = "Method", values_to = "Abundance")
`summarise()` ungrouping output (override with `.groups` argument)
# turn zeroes to NA so they don't plot
species_sums_abun_table <- na_if(species_sums_abun_table,0)
species_sums_abun_table
For each species, plot side-by-side comparison of abundance (summed over whole study) using each method
# First create a custom color scale to make this pretty
myColors <- colorRampPalette(brewer.pal(11,"Spectral"))(55)
names(myColors) <- levels(unique(species_sums_abun_table$CommonName))
colScale <- scale_colour_manual(name = "CommonName",values = myColors)
species_abun_sum_plot <- ggplot(species_sums_abun_table, aes(x = Abundance, y = reorder(CommonName, Abundance, function(x){sum(x,na.rm = TRUE)}), color = CommonName)) +
geom_point(size = 5) +
facet_wrap(~fct_rev(Method), scales = "free") +
theme_bw() +
xlab("Abundance") +
ylab("") +
colScale +
theme(legend.position = "none")
species_abun_sum_plot
Export plot
ggsave(filename = "Figures/species_abun_sum_plot.eps", plot = species_abun_sum_plot, units = c("in"), width = 7, height = 8, dpi = 300)
I will try PCoA, PCA (the Euclidean PCoA) and NMDS ordinations in combination with different tranformations and distance metrics in order to see which explain the most variance in the dataset.
PCA is essentially a type of PCoA using the Euclidean distance matrix as input. When combined with a log-ratio transformation of the count table, this is deemed appropriate for compositional datasets. It is also recommended as a first step in exploratory analyses of sequencinging datasets.
First do a CLR, centered log ratio transformation of the absolute abundance data (after filtering), as suggested by Gloor et al. 2017
# Estimate covariance matrix for CLR-transformed ASV table
clr_asv_table_ps <- data.frame(compositions::clr(otu_table(ps)))
Generate the PCA and visualize axes
# Generate a Principle Component Analysis (PCA) and evaluated based on the eigen decomposition from sample covariance matrix.
lograt_pca <- prcomp(clr_asv_table_ps)
# NOTE- this is equivalent to first making a Euclidean distance matrix using the CLR data table and then running a PCoA. A Euclidean distance matrix of a log-transformed data table = an Aitchison distance matrix. So this is equivalent to the compositional methods listed in Gloor et al.
# Visual representation with a screeplot
lograt_variances <- as.data.frame(lograt_pca$sdev^2/sum(lograt_pca$sdev^2)) %>% #Extract axes
# Format to plot
select(PercVar = 'lograt_pca$sdev^2/sum(lograt_pca$sdev^2)') %>%
rownames_to_column(var = "PCaxis") %>%
data.frame
head(lograt_variances)
# Plot screeplot
ggplot(lograt_variances, aes(x = as.numeric(PCaxis), y = PercVar)) +
geom_bar(stat = "identity", fill = "grey", color = "black") +
theme_minimal() +
theme(axis.title = element_text(color = "black", face = "bold", size = 10),
axis.text.y = element_text(color = "black", face = "bold"),
axis.text.x = element_blank()) +
labs(x = "PC axis", y = "% Variance", title = "Log-Ratio PCA Screeplot, CLR Tranformation")
Total variance explained by first three axes= 15.7 + 10.5 + 10.0 = 36.2%. Since the second and third axes are similar, plot in 3D with 3 axes.
Visualize the PCA-
# Extract variances from the clr pca
pca_lograt_frame <- data.frame(lograt_pca$x) %>%
rownames_to_column(var = "SampleID")
# Merge metadata into the pcoa data table
pca_lograt_frame <- left_join(pca_lograt_frame, metadata, by = "SampleID")
head(pca_lograt_frame)
# Select eigenvalues from dataframe, round to 4 places and multiply by 100 for plotting. These will be the axes for the 3-D plot
eigenvalues<-round(lograt_variances[,2], digits = 4)*100
# Plotly - 3-D
pca_lograt <- plot_ly(pca_lograt_frame, type='scatter3d', mode='markers',
x=~PC1,y=~PC2,z=~PC3,colors=~brewer.pal(11,'Paired'),
color=~Station, symbols = c('circle','diamond'), symbol=~Bayside)%>%
layout(font=list(size=12),
title='CLR-Euclidean PCA',
scene=list(xaxis=list(title=paste0('Co 2 ',eigenvalues[2],'%'),
showticklabels=FALSE,zerolinecolor='black'),
yaxis=list(title=paste0('Co 3 ',eigenvalues[3],'%'),
showticklabels=FALSE,zerolinecolor='black'),
zaxis=list(title=paste0('Co 1 ',eigenvalues[1],'%'),
showticklabels=FALSE,zerolinecolor='black')))
# pca_lograt
# save in "Embedded_figures" directory so that it can be hosted at Github and embedded in this notebook
withr::with_dir('Embedded_figures', htmlwidgets::saveWidget(as_widget(pca_lograt), file="pca_lograt.html", selfcontained = F))
Summary The CLR-Euclidean PCA reveals there is some separation according to East vs West. The PCA only explains ~36% of the variance so keep going with different ordinations to see if there is a better representation
The more traditional approach to ordinations is to do a PCoA on a distance matrix such as Bray-Curtis, Jaccard, or Unifrac. When combined with a transformation, they become more appropriate for NGS data. One such common transformation is the Hellinger transformation.
The different distance matrices also tell you a few different things about the dataset so I will run try different one to try to see if I can tease those out.
Before calculating any distance matrix, do a transformation of the filtered count table. Hellinger transformation is the square root of the relative abundance, so calculate it based on the ps_ra object:
ps_hellinger <- transform_sample_counts(ps_ra, function(x){sqrt(x)})
First, Jaccard, which builds the distance matrix based on presence/absence between samples. It does not take into account relative abundance of the taxa. Therefore this functions well for determining differences driven by rare taxa, which are weighed the same as abundant taxa.
jac_dmat<-vegdist(otu_table(ps_hellinger),method="jaccard") # Jaccard dist metric
pcoa_jac<-ape::pcoa(jac_dmat) # perform PCoA
# Extract variances from pcoa, from jaccard calculated dist. metric
jac_variances <- data.frame(pcoa_jac$values$Relative_eig) %>%
select(PercVar = 'pcoa_jac.values.Relative_eig') %>%
rownames_to_column(var = "PCaxis") %>%
data.frame
head(jac_variances)
# Make a screeplot
ggplot(jac_variances, aes(x = as.numeric(PCaxis), y = PercVar)) +
geom_bar(stat = "identity", fill = "grey", color = "black") +
theme_minimal() +
theme(axis.title = element_text(color = "black", face = "bold", size = 10),
axis.text.y = element_text(color = "black", face = "bold"),
axis.text.x = element_blank()) +
labs(x = "PC axis", y = "% Variance", title = "Jaccard PCoA Screeplot")
The first two axes (19.0 + 9.6 = 28.6) are OK. But plot the first 3 axes since the 2nd and 3rd explain a similar amount of variance, (19.0 + 9.6 + 8.4 = 37% total variance explained)
Plot in 3D with Plotly
# Extract variances from the jaccard pcoa
pcoa_jac_df <- data.frame(pcoa_jac$vectors) %>%
rownames_to_column(var = "SampleID")
# Merge metadata into the pcoa data table
pcoa_jac_df <- left_join(pcoa_jac_df, metadata, by = "SampleID")
head(pcoa_jac_df)
# Select eigenvalues from dataframe, round to 4 places and multiply by 100 for plotting. These will be the axes for the 3-D plot
eigenvalues<-round(jac_variances[,2], digits = 4)*100
# Plotly - 3-D
pcoa_jaccard <- plot_ly(pcoa_jac_df, type='scatter3d', mode='markers',
x=~Axis.2,y=~Axis.3,z=~Axis.1,colors=~brewer.pal(11,'Paired'),
color=~Station, symbols = c('circle','diamond'), symbol=~Bayside)%>%
layout(font=list(size=12),
title='PCoA Jaccard Distance',
scene=list(xaxis=list(title=paste0('Co 2 ',eigenvalues[2],'%'),
showticklabels=FALSE,zerolinecolor='black'),
yaxis=list(title=paste0('Co 3 ',eigenvalues[3],'%'),
showticklabels=FALSE,zerolinecolor='black'),
zaxis=list(title=paste0('Co 1 ',eigenvalues[1],'%'),
showticklabels=FALSE,zerolinecolor='black')))
# pcoa_jaccard
# save in "Embedded_figures" directory so that it can be hosted at Github and embedded in this notebook
withr::with_dir('Embedded_figures', htmlwidgets::saveWidget(as_widget(pcoa_jaccard), file="pcoa_jaccard.html", selfcontained = F))
The Jaccard-PCoA shows some separation along axis 2 and axis 3 in East vs West differences.
Next, try a Bray-Curtis distance matrix with PCoA, which builds the distance matrix based on presence/absence between samples and relative abundance differences. This ordination will represent well the differences in samples that are driven by taxa with high relative abundances.
NOTE: I need to use a correction here for negative eigenvalues. Read more here
bray_dmat<-vegdist(otu_table(ps_hellinger),method="bray") # Bray-Curtis dist metric
pcoa_bray<-ape::pcoa(bray_dmat) # perform PCoA in ape. But getting negative eigenvalues, so need to add correction. wcmdscale from base R also performs PCoA and can add cailliez correction
pcoa_bray <- wcmdscale(bray_dmat, eig = TRUE, add = "cailliez")
# check out summary of PCoA
eigenvals(pcoa_bray) %>%
summary() -> ev
ev
Importance of components:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
Eigenvalue 6.3464 3.2976 2.85913 1.62791 1.33454 1.24845 1.00909 0.90344
Proportion Explained 0.2111 0.1097 0.09511 0.05415 0.04439 0.04153 0.03357 0.03005
Cumulative Proportion 0.2111 0.3208 0.41591 0.47006 0.51445 0.55598 0.58955 0.61960
[,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
Eigenvalue 0.87308 0.77983 0.71209 0.65600 0.60628 0.54828 0.4990 0.4418
Proportion Explained 0.02904 0.02594 0.02369 0.02182 0.02017 0.01824 0.0166 0.0147
Cumulative Proportion 0.64864 0.67458 0.69827 0.72009 0.74026 0.75849 0.7751 0.7898
[,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24]
Eigenvalue 0.40560 0.39289 0.3668 0.3488 0.33712 0.33131 0.30233 0.285332
Proportion Explained 0.01349 0.01307 0.0122 0.0116 0.01121 0.01102 0.01006 0.009491
Cumulative Proportion 0.80328 0.81635 0.8285 0.8401 0.85136 0.86238 0.87244 0.881932
[,25] [,26] [,27] [,28] [,29] [,30] [,31]
Eigenvalue 0.268800 0.255859 0.24770 0.239363 0.226397 0.217778 0.198829
Proportion Explained 0.008941 0.008511 0.00824 0.007962 0.007531 0.007244 0.006614
Cumulative Proportion 0.890874 0.899385 0.90762 0.915586 0.923117 0.930361 0.936975
[,32] [,33] [,34] [,35] [,36] [,37] [,38]
Eigenvalue 0.194478 0.186212 0.167167 0.156242 0.15362 0.151123 0.139519
Proportion Explained 0.006469 0.006194 0.005561 0.005197 0.00511 0.005027 0.004641
Cumulative Proportion 0.943444 0.949639 0.955199 0.960397 0.96551 0.970534 0.975175
[,39] [,40] [,41] [,42] [,43] [,44] [,45]
Eigenvalue 0.133554 0.127736 0.124257 0.110435 0.106545 0.085716 0.058069
Proportion Explained 0.004443 0.004249 0.004133 0.003674 0.003544 0.002851 0.001932
Cumulative Proportion 0.979617 0.983866 0.987999 0.991673 0.995217 0.998068 1.000000
# extract variances and put in tibble
bray_variances <- NULL
for (i in 1:length(eigenvals(pcoa_bray))){
bray_variances[i] <- eigenvals(pcoa_bray)[i]/sum(eigenvals(pcoa_bray))
}
# Extract variances from pcoa, from calculated dist. metric
bray_variances <- tibble(round(bray_variances,3)) %>%
select(PercVar = 'round(bray_variances, 3)') %>%
rownames_to_column(var = "PCaxis") %>%
data.frame
head(bray_variances)
# Make a screeplot
ggplot(bray_variances, aes(x = as.numeric(PCaxis), y = PercVar)) +
geom_bar(stat = "identity", fill = "grey", color = "black") +
theme_minimal() +
theme(axis.title = element_text(color = "black", face = "bold", size = 10),
axis.text.y = element_text(color = "black", face = "bold"),
axis.text.x = element_blank()) +
labs(x = "PC axis", y = "% Variance", title = "Bray-Curtis PCoA Screeplot")
The first two axes (21.1 + 11.0) are pretty good again but I am still going to experiment in the plot with the 3rd axis since it is similar to the second (9.5%; total variance explained = 41.6%)
Plot in 3D with Plotly
# Extract variances from the pcoa
There were 18 warnings (use warnings() to see them)
pcoa_bray_df <- data.frame(pcoa_bray$points) %>%
rownames_to_column(var = "SampleID")
# Merge metadata into the pcoa data table
pcoa_bray_df <- left_join(pcoa_bray_df, metadata, by = "SampleID")
head(pcoa_bray_df)
# Select eigenvalues from dataframe, round to 4 places and multiply by 100 for plotting. These will be the axes for the 3-D plot
eigenvalues<-round(bray_variances[,2], digits = 4)*100
# Plotly - 3-D
pcoa_bray <- plot_ly(pcoa_bray_df, type='scatter3d', mode='markers',
x=~Dim2, y=~Dim3, z=~Dim1, colors=~brewer.pal(11,'Paired'),
color=~Station, symbols = c('circle','diamond'), symbol=~Bayside)%>%
layout(font=list(size=12),
title='PCoA Bray-Curtis Distance',
scene=list(xaxis=list(title=paste0('Co 2 ',eigenvalues[2],'%'),
showticklabels=FALSE,zerolinecolor='black'),
yaxis=list(title=paste0('Co 3 ',eigenvalues[3],'%'),
showticklabels=FALSE,zerolinecolor='black'),
zaxis=list(title=paste0('Co 1 ',eigenvalues[1],'%'),
showticklabels=FALSE,zerolinecolor='black')))
# pcoa_bray
# save in "Embedded_figures" directory so that it can be hosted at Github and embedded in this notebook
withr::with_dir('Embedded_figures', htmlwidgets::saveWidget(as_widget(pcoa_bray), file="pcoa_bray.html", selfcontained = F))
`arrange_()` was deprecated in dplyr 0.7.0.
Please use `arrange()` instead.
See vignette('programming') for more help
These results along axes 1, 2, and 3 are similar to Jaccard, but there is MORE separation along axis 2, indicating that incorporating the differences in abundance helps explain more variance in the dataset.
Lastly, try a non-metric dimensional scaling ordination. PCA/PCoA are metric and attempt to rotate axes to fit the distance matrix distribution. An NMDS represents the data in 2-axes, by constraining the distribution of the points. Similar to above, this can be combined with different pre-treatment of the data.
First try the compositional approach, an NMDS on CLR-tranformed data using the Euclidean distances (aka Aitchison distance)
euc_dmat<-dist(clr_asv_table_ps, method = "euclidean") # Build the Aitchison distance matrix
There were 50 or more warnings (use warnings() to see the first 50)
euc_nmds <- metaMDS(euc_dmat, k=2, autotransform=FALSE) # Run the ordination
Run 0 stress 0.2105436
Run 1 stress 0.210743
... Procrustes: rmse 0.01868597 max resid 0.06267382
Run 2 stress 0.2284121
Run 3 stress 0.2281367
Run 4 stress 0.2154902
Run 5 stress 0.2169974
Run 6 stress 0.2128146
Run 7 stress 0.2123984
Run 8 stress 0.2129377
Run 9 stress 0.2321112
Run 10 stress 0.2129288
Run 11 stress 0.2324063
Run 12 stress 0.2127399
Run 13 stress 0.2110277
... Procrustes: rmse 0.02376164 max resid 0.09749588
Run 14 stress 0.2148974
Run 15 stress 0.2109046
... Procrustes: rmse 0.01881004 max resid 0.06376019
Run 16 stress 0.2150601
Run 17 stress 0.2314828
Run 18 stress 0.2112384
Run 19 stress 0.2128146
Run 20 stress 0.2126376
*** No convergence -- monoMDS stopping criteria:
1: no. of iterations >= maxit
19: stress ratio > sratmax
euc_nmds$stress #Check the stress. Less than 0.1 is good. Less than 0.05 is better. This will be different each time, since it is iteratively finding a unique solution each time (although the should look similar)
[1] 0.2105436
# Extract points from nmds and merge into data frame with metadata
euc_nmds_df <- data.frame(euc_nmds$points) %>%
rownames_to_column(var = "SampleID")
# Merge metadata into the pcoa data table
euc_nmds_df <- left_join(euc_nmds_df, metadata, by = "SampleID")
head(euc_nmds_df)
## Plotting euclidean distance NMDS
nmds_aitch <- ggplot(euc_nmds_df,aes(x = MDS1, y = MDS2, color = Station, shape = Bayside)) +
geom_point(size = 4) +
scale_color_brewer(palette="Paired") +
theme_bw() +
labs(x = "NMDS 1", y = "NMDS 2", title = paste0('Aitchison Distance NMDS, Stress = ', round(euc_nmds$stress,2))) +
coord_fixed(ratio = 1)
nmds_aitch
ggsave("figures/nmds_aitch.eps",nmds_aitch, width = 7, height = 5, units = c("in"))
The above has a relatively high stress (>0.2) so should be interpreted with caution. But it does show some separation East vs West along NMDS 1.
Next try a Jaccard NMDS, which will represent differences in presence/absence among samples, emphasizing both abundant and rare taxa the same
jac_nmds <- metaMDS(jac_dmat, k=2, autotransform=FALSE) # Run the ordination. Distance matrix was already calculated above
Run 0 stress 0.1627003
Run 1 stress 0.1635518
Run 2 stress 0.1913278
Run 3 stress 0.187493
Run 4 stress 0.1850804
Run 5 stress 0.1574296
... New best solution
... Procrustes: rmse 0.09013991 max resid 0.3060624
Run 6 stress 0.1496846
... New best solution
... Procrustes: rmse 0.0611786 max resid 0.3342008
Run 7 stress 0.1758766
Run 8 stress 0.1496646
... New best solution
... Procrustes: rmse 0.05213047 max resid 0.3264531
Run 9 stress 0.1512066
Run 10 stress 0.1496492
... New best solution
... Procrustes: rmse 0.002075288 max resid 0.01112514
Run 11 stress 0.1511994
Run 12 stress 0.1747511
Run 13 stress 0.164175
Run 14 stress 0.1635021
Run 15 stress 0.1578622
Run 16 stress 0.1741207
Run 17 stress 0.1805795
Run 18 stress 0.150871
Run 19 stress 0.150871
Run 20 stress 0.1809297
*** No convergence -- monoMDS stopping criteria:
1: no. of iterations >= maxit
19: stress ratio > sratmax
jac_nmds$stress #Check the stress. Less than 0.1 is good. Less than 0.5 is better. This will be different each time, since it is iteratively finding a unique solution each time (although the should look similar)
[1] 0.1496492
# Extract points from nmds and merge into data frame with metadata
jac_nmds_df <- data.frame(jac_nmds$points) %>%
rownames_to_column(var = "SampleID")
# Merge metadata into the pcoa data table
jac_nmds_df <- left_join(jac_nmds_df, metadata, by = "SampleID")
head(jac_nmds_df)
## Plotting euclidean distance NMDS
nmds_jaccard <- ggplot(jac_nmds_df,aes(x = MDS1, y = MDS2, color = Station, shape = Bayside)) +
geom_point(size = 4) +
scale_color_brewer(palette="Paired") +
theme_bw() +
labs(x = "NMDS 1", y = "NMDS 2", title = paste0('Jaccard Distance NMDS, Stress = ', round(jac_nmds$stress,2))) +
coord_fixed(ratio = 1)
nmds_jaccard
ggsave("figures/nmds_jaccard.eps",nmds_jaccard, width = 7, height = 5, units = c("in"))
This is still a moderately high stress (>0.1) so should be interpreted with caution. Similar to Aitchison-distance nMDS but there is a little more separation of East vs West on NMDS 2 axis.
Next try a Bray-Curis NMDS, which will represent differences in presence/absence among samples and relative abundance, thus emphasizing impacts of highly abundant taxa.
bray_nmds <- metaMDS(bray_dmat, k=2, autotransform=FALSE) # Run the ordination. Distance matrix was already calculated above
Run 0 stress 0.1628608
Run 1 stress 0.1496857
... New best solution
... Procrustes: rmse 0.08605306 max resid 0.3199495
Run 2 stress 0.1575236
Run 3 stress 0.1648221
Run 4 stress 0.1496852
... New best solution
... Procrustes: rmse 0.001000773 max resid 0.005543388
... Similar to previous best
Run 5 stress 0.1816327
Run 6 stress 0.1574077
Run 7 stress 0.16342
Run 8 stress 0.1495163
... New best solution
... Procrustes: rmse 0.05077312 max resid 0.3254243
Run 9 stress 0.1496857
... Procrustes: rmse 0.05076782 max resid 0.3264084
Run 10 stress 0.1569837
Run 11 stress 0.1700137
Run 12 stress 0.149831
... Procrustes: rmse 0.05229099 max resid 0.3259367
Run 13 stress 0.1711916
Run 14 stress 0.1634202
Run 15 stress 0.164822
Run 16 stress 0.1496496
... Procrustes: rmse 0.01267154 max resid 0.07708813
Run 17 stress 0.1667643
Run 18 stress 0.1758516
Run 19 stress 0.1660923
Run 20 stress 0.1508713
*** No convergence -- monoMDS stopping criteria:
1: no. of iterations >= maxit
19: stress ratio > sratmax
bray_nmds$stress #Check the stress. Less than 0.1 is good. Less than 0.5 is better. This will be different each time, since it is iteratively finding a unique solution each time (although the should look similar)
[1] 0.1495163
# Extract points from nmds and merge into data frame with metadata
bray_nmds_df <- data.frame(bray_nmds$points) %>%
rownames_to_column(var = "SampleID")
# Merge metadata into the pcoa data table
bray_nmds_df <- left_join(bray_nmds_df, metadata, by = "SampleID")
head(bray_nmds_df)
## Plotting euclidean distance NMDS
nmds_bray <- ggplot(bray_nmds_df,aes(x = MDS1, y = MDS2, color = Station, shape = Bayside)) +
geom_point(size = 4) +
scale_color_brewer(palette="Paired") +
theme_bw() +
labs(x = "NMDS 1", y = "NMDS 2", title = paste0('Bray-Curtis Distance NMDS, Stress = ', round(bray_nmds$stress,2))) +
coord_fixed(ratio = 1)
nmds_bray
ggsave("figures/nmds_bray.eps",nmds_bray, width = 7, height = 5, units = c("in"))
Very similar to Jaccard results. Moderately high stress (0.15)
The ordination that explained the most variance in the eDNA dataset was the PCoA using the Bray-Curtis dissimilarity matrix after Hellinger transformation. This is similar to the approach presented in Lacoursière‐Roussel et al. 2018.
Recreate, in 2D, the first two axes of the ordination (PCoA with Bray distance matrx/ Hellinger transformation) and use envfit from vegan to test and fit environmental variables.
If not making 3D plots, can do this directly in phyloseq (eg. https://www.gdc-docs.ethz.ch/MDA/handouts/MDA20_PhyloseqFormation_Mahendra_Mariadassou.pdf)
—— Fix below after plot above is fixed- Cant use phyloseqs pcoa ordination with cailliez correction
Check how samples differ in the ordination according to different environmental variables
plot_ordination(ps_hellinger, ps_hellinger_bray_pcoa, color = "Bayside") +
geom_point(size = 4) +
stat_ellipse(aes(group = Bayside)) +
ggtitle('Bray Curtis PCoA') +
coord_fixed(ratio = 1) +
theme_bw()
Summary: There is overlap of the two, but there are also many EAST samples that fall outside and do no look similar to WEST samples. The transition correlates with axis 2. The WEST samples are more closely clustered together than EAST samples.
plot_ordination(ps_hellinger, ps_hellinger_bray_pcoa, color = "Habitat") +
geom_point(size = 4) +
stat_ellipse(aes(group = Habitat)) +
ggtitle('Bray Curtis PCoA') +
coord_fixed(ratio = 1) +
theme_bw()
Summary there doesn’t seem to be any effect of habitat type
plot_ordination(ps_hellinger, ps_hellinger_bray_pcoa, color = "Date") +
geom_point(size = 4) +
stat_ellipse(aes(group = Date)) +
ggtitle('Bray Curtis PCoA') +
coord_fixed(ratio = 1) +
theme_bw()
Summary There seems to be a continuous transition from July 22 to Sept. 2 but isn’t parallel to either axis 1 or 2.
# vegan doesn't do a pcoa. try cmdscale from base R on the bray curtis distance matrix (after hellinger transformation)
pcoa <- wcmdscale(bray_dmat, eig = TRUE)
eigenvals(pcoa) %>%
summary() -> ev
ev
Importance of components:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
Eigenvalue 4.2258 2.1784 1.8551 1.01077 0.78507 0.74604 0.57803 0.49798
Proportion Explained 0.2769 0.1428 0.1216 0.06624 0.05145 0.04889 0.03788 0.03263
Cumulative Proportion NA NA NA NA NA NA NA NA
[,9] [,10] [,11] [,12] [,13] [,14] [,15] [,16]
Eigenvalue 0.48126 0.4089 0.35895 0.32230 0.29289 0.25365 0.2198 0.1816
Proportion Explained 0.03154 0.0268 0.02352 0.02112 0.01919 0.01662 0.0144 0.0119
Cumulative Proportion NA NA NA NA NA NA NA NA
[,17] [,18] [,19] [,20] [,21] [,22] [,23]
Eigenvalue 0.15789 0.15153 0.129958 0.120610 0.115693 0.101967 0.08697
Proportion Explained 0.01035 0.00993 0.008517 0.007904 0.007582 0.006682 0.00570
Cumulative Proportion NA NA NA NA NA NA NA
[,24] [,25] [,26] [,27] [,28] [,29] [,30]
Eigenvalue 0.07843 0.069186 0.060555 0.054821 0.051491 0.036271 0.029569
Proportion Explained 0.00514 0.004534 0.003968 0.003593 0.003374 0.002377 0.001938
Cumulative Proportion NA NA NA NA NA NA NA
[,31] [,32] [,33] [,34] [,35] [,36] [,37]
Eigenvalue 0.024343 0.023518 0.018367 0.013871 0.0077006 0.0052630 -2.106e-05
Proportion Explained 0.001595 0.001541 0.001204 0.000909 0.0005046 0.0003449 1.380e-06
Cumulative Proportion NA NA NA NA NA NA NA
[,38] [,39] [,40] [,41] [,42] [,43]
Eigenvalue -0.0077983 -0.0101807 -0.017069 -0.027714 -0.037663 -0.046618
Proportion Explained 0.0005111 0.0006672 0.001119 0.001816 0.002468 0.003055
Cumulative Proportion NA NA NA NA NA NA
[,44] [,45] [,46]
Eigenvalue -0.060747 -0.100417 -0.16686
Proportion Explained 0.003981 0.006581 0.01093
Cumulative Proportion NA NA NA